import React,{useState,useRef} from 'react'
import { Toast } from 'antd-mobile'
import { List,AutoSizer } from 'react-virtualized'

import { setChooseCity } from '../../utils'

import './index.scss'

export default function VirtualizedList(props) {

  const {data:_data,history}=props

  const [index, setIndex] = useState('#')

  const virtualizedList = useRef()
  
  const getTitle=(s)=>{
    switch (s) {
      case '#':
        return '当前定位'
      case 'hot':
        return '热门城市'
      default:
        return s
    }
  }

  const getRowHeight=({index})=>{
    let count=1
    if(_data.labels[index]!=='#'){
      count=_data.data[_data.labels[index]].length
    } 
    return 41*count+29
  }

  const setLocation=async (cityName)=>{
    Toast.loading('loading...',0)
    await setChooseCity(cityName)
    Toast.hide()
    history.replace('/home')
  }

  function rowRenderer({
    key, // Unique key within array of rows
    index, // Index of row within collection
    isScrolling, // 是否在滚动
    isVisible, // This row is visible within the List (eg it is not an overscanned row)
    style, // Style object to be applied to row (to position it)
  }) {
    const {data,labels}=_data
    return (
      <div key={key} style={style} className='letter-group'>
        <div className='city-letter'>
          {getTitle(labels[index])}
        </div>
        <div className='city-list'>
          {
            labels[index]!=='#'?
           data[labels[index]].map(i=><div key={i.value} className='city' onClick={()=>setLocation(i.label)}>
              {i.label}
            </div>):
            <div className='city' onClick={()=>setLocation(data[labels[index]])}>{data[labels[index]]}</div>
          }
        </div>
      </div>
    )
  }

  return (
    <AutoSizer>
      {
        ({width,height})=>(
          <div>
            <List
              ref={virtualizedList}
              width={width}
              height={height}
              rowCount={_data.labels.length}
              rowHeight={getRowHeight}
              rowRenderer={rowRenderer}
              scrollToAlignment='start'//保证被点击行出现在页面顶部
              onRowsRendered={({startIndex})=>startIndex!==index?setIndex(_data.labels[startIndex]):null}
            />
            <div className='city-index'>
              {
                _data.labels.map(i=><div key={i} className={'item '+(index===i?'active':'')} onClick={()=>{
                  if(index===i)return
                  setIndex(i)
                  virtualizedList.current.scrollToRow(_data.labels.findIndex(_i=>_i===i))
                }}>
                  {i==='hot'?'热':i}
                  </div>)
              }
            </div>
          </div>
      )}
    </AutoSizer>
  )
}

